package HTTP

import (
	"SQL/myDB"
	"net/http"
)

//删除群成员：
//s groupID string,[memberID string]
//r Message string,
//  nil
func deleteGroupMember(w http.ResponseWriter, req *http.Request) {
	var (
		code   int         = Success
		msg    string      = ""
		result interface{} = nil
	)
	defer func() {
		writeResponse(code, msg, result, w)
	}()

	err := initHandle(w, req)
	if err != nil {
		code = errParseForm
		msg = err.Error()
		return
	}

	userID := req.FormValue("userID")
	groupID := req.FormValue("groupID")
	memberID := req.Form["memberID"]
	code, msg, result = dealDeleteGroupMember(groupID, memberID, userID)
}
func dealDeleteGroupMember(groupID string, memberID []string, userID string) (code int, msg string, result interface{}) {
	if userID == "" {
		code = errEmtpyID
		msg = "userID is empty"
		return
	}
	code, msg = IsManager(userID)
	if code != Success {
		return
	}
	ok := IsUserIDInMemberID(userID, memberID)
	if ok {
		code = errInvalidID
		msg = "userID is in memberID,which means delete himself"
		return
	}

	if groupID == "" {
		code = errEmtpyID
		msg = "groupID is empty!"
		return
	}
	if len(memberID) == 0 {
		code = errEmtpyID
		msg = "memberID is empty!"
		return
	}
	code, msg = IsGroupID(groupID)
	if code != Success {
		return
	}

	db, err := myDB.GetDB()
	if err != nil {
		code = errOpenDB
		msg = err.Error()
		return
	}

	tx, err := db.Begin()
	if err != nil {
		code = errBeginTx
		msg = err.Error()
		return
	}

	defer func() {
		if code != Success {
			err := tx.Rollback()
			if err != nil {
				code = errEndTx
				msg = err.Error()
			}
		}
	}()

	err = myDB.TxExecMultiSql(tx, "delete from members where groupID=$2 and userID=$1", memberID, groupID)
	if err != nil {
		code = errDBExecFailed
		msg = err.Error()
		return
	}

	err = tx.Commit()
	if err != nil {
		code = errEndTx
		msg = err.Error()
	}
	return Success, "", nil
}

func IsUserIDInMemberID(userID string, memberID []string) bool {
	for _, val := range memberID {
		if val == userID {
			return true
		}
	}
	return false
}
